const {Lease, Ask, House, User, UserInfo} = require('../db/model/index')
const {Op} = require('sequelize')

const getLeaseList = async ({askId, ownerId, status, createTime, pageIndex, pageSize}) => {
  const where = {}

  const whereUser = {}

  const whereOp = {}

  if (askId !== undefined) {
    where.askId = askId
  }

  if (ownerId !== undefined) {
    whereUser.uid = ownerId
  }

  if (status !== undefined) {
    whereOp.status = status
  }

  if (createTime.length) {
    whereOp[`created_at`] = {
      [Op.gte]: createTime[0],
      [Op.lte]: createTime[1]
    }
  }


  const result = await Lease.findAndCountAll({
    limit: +pageSize,
    offset: pageSize * pageIndex,
    order: [
      [ 'id', 'desc' ]
    ],
    where: whereOp,
    include: [
      {
        model: Ask,
        where: where,
        include: [
          {
            model: House,
            where: whereUser,
            include: [
              {
                model: User,
                as: 'user',
                attributes: [ 'nickName' ]
              }
            ]
          },
          {
            model: User,
            attributes: [ 'nickName' ]
          }
        ]
      }
    ]
  })

  return {
    count: result.count,
    data: result.rows
  }
}

const createLease = async ({content, askId, status}) => {
  const result = await Lease.create({
    content,
    askId,
    status
  })

  const data = result.dataValues

  return data
}

const updateLease = async ({content, status, id}) => {
  const whereOpt = {
    id
  }
  const result = await Lease.update({
    content,
    status
  }, {
    where: whereOpt
  })

  const data = result.length > 0

  return data
}

const delLease = async (id) => {
  const result = await Lease.destroy({
    where: {
      id
    }
  })

  return result > 0
}

const getLeaseOne = async (id) => {
  const result = await Lease.findOne({
    where: {
      id
    },
    include: [
      {
        model: Ask,
        include: [
          {
            model: House,
            include: [
              {
                model: User,
                as: 'user',
                attributes: {
                  exclude: [ 'password' ]
                },
                include: [
                  {
                    model: UserInfo
                  }
                ]
              }
            ]
          },
          {
            model: User,
            attributes: {
              exclude: [ 'password' ]
            },
            include: [
              {
                model: UserInfo
              }
            ]
          }
        ]
      }
    ]
  })

  return result.dataValues
}

module.exports = {
  getLeaseList,
  createLease,
  updateLease,
  delLease,
  getLeaseOne
}
